# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from google.appengine.api import users
from google.appengine.api.datastore_types import GeoPt

from django.http import HttpResponseRedirect

from settings import DEFAULT_LANG

from apis import people_api, routes_api, gear_api, stats_api, outusers
from siteutils import render_to_response, errorpage, escape_and_strip, requires_site_user
from siteutils.language import _, get_support_langs, get_current_lang, save_current_lang


def check_name(nickname):
    if users.is_current_user_admin():
        return True
    if nickname.lower().find("magicycle") >= 0 or\
       nickname.find(u'迈记') >= 0 or\
       nickname.lower().find("magi cycle") >= 0 or\
       nickname.lower().find("magic cycle") >= 0:
        return False
    return True


def ridersindex(request):
    context = {"option": {"enable_gmap": True, },
               "subtitle": _("Riders"),
               }
    return render_to_response("ridersmap.html", context)


def joinus(request):
    site = request.GET.get("site", None)
    if request.method != "POST" and site:
        if not outusers.check_outsite_user(request, site):
            return errorpage("Login Failed, pls retry")

    outsiteuser = outusers.get_outsite_user()
    if not outsiteuser:
        return HttpResponseRedirect("/login/")

    user = people_api.get_current_user()
    if user: # user exist
        outusers.update_user_info(user, outsiteuser, request)
        return HttpResponseRedirect("/riders/%s/" % (user.uid))

    if request.method == "POST":
        try:
            agree = request.POST.get("agree", 0)
            if not agree:
                raise Exception("You must agress term of service")

            uid = escape_and_strip(request.POST.get("uid", ""))
            if not check_name(uid):
                raise Exception("Invalid Login Account")
            nickname = escape_and_strip(request.POST.get("nickname", ""))
            if not check_name(nickname):
                raise Exception("Invalid Nickname")
            intro = escape_and_strip(request.POST.get("intro", ""))
            email = escape_and_strip(request.POST.get("email", ""))
            photourl = escape_and_strip(request.POST.get("photourl", ""))
            language = get_current_lang()

            siteuser = people_api.new_site_user(outsiteuser, uid, nickname, intro=intro,
                photourl=photourl, language=language, email=email)
            outusers.update_user_info(siteuser, outsiteuser, request)
        except Exception, e:
            from django.utils.encoding import force_unicode

            context = {"outsiteuser": outsiteuser,
                       "stats": stats_api.get_stats(),
                       "error_msg": force_unicode(e)}
            return render_to_response("joinus.html", context)

        if siteuser:
            return HttpResponseRedirect("/riders/%s/editprofile/" % (uid))
        else:
            return errorpage("Can not create user %s" % (uid))

    context = {"outsiteuser": outsiteuser,
               "stats": stats_api.get_stats(), }
    return render_to_response("joinus.html", context)


@requires_site_user
def editprofile(request, uid):
    user = people_api.get_user_by_uid(uid)

    if not user:
        return errorpage("Can not find user %s" % (uid))

    if user.uid != people_api.get_current_user().uid and not users.is_current_user_admin():
        return errorpage("unauthorized")

    if request.method == "POST":
        try:
            new_uid = escape_and_strip(request.POST.get("uid", ""))
            if new_uid != uid and not users.is_current_user_admin():
                raise Exception("unauthorized")

            userphotourl = escape_and_strip(request.POST.get("userphotourl", ""))
            nickname = escape_and_strip(request.POST.get("nickname", ""))
            if not check_name(nickname):
                raise Exception("Invalid Nickname")

            email = escape_and_strip(request.POST.get("email", ""))
            timezone = float(escape_and_strip(request.POST.get("timezone", "8")))
            user_language = escape_and_strip(request.POST.get("user_language", DEFAULT_LANG))
            intro = escape_and_strip(request.POST.get("intro", ""))
            user_units = escape_and_strip(request.POST.get("user_units", "metric"))
            country = escape_and_strip(request.POST.get("country", ""))
            state = escape_and_strip(request.POST.get("state", ""))
            city = escape_and_strip(request.POST.get("city", ""))
            user_lat = escape_and_strip(request.POST.get("user_lat", ""))
            user_lon = escape_and_strip(request.POST.get("user_lon", ""))
        except Exception, e:
            return errorpage(str(e))

        for site in outusers.OutSitesTypes:
            name = "update_activity_%s" % site
            enable = request.POST.get(name, False)
            outuser = user.OutUsers.get(site, None)
            if outuser:
                profile = {
                    "enable_twitter": False,
                    }
                if outuser.is_tweetable and enable:
                    profile["enable_twitter"] = True

                people_api.save_outuser_profile(outuser.uid, profile)

        profile = {
            "photourl": userphotourl,
            "name": nickname,
            "email": email,
            "timezone": timezone,
            "language": user_language,
            "intro": intro,
            "units": user_units,
            "country": country,
            "state": state,
            "city": city,
            }
        if user_lat and user_lon:
            try:
                profile["location"] = GeoPt(float(user_lat), float(user_lon))
            except Exception:
                pass

        people_api.save_user_profile(uid, profile)
        save_current_lang(user_language)
        return HttpResponseRedirect("/riders/%s/" % (uid))

    context = {"languages": get_support_langs(),
               "current_lang": get_current_lang(),
               "edituser": user,
               "option": {"enable_gmap": True, },
               "subtitle": _("Edit Your Profile"),
               }
    return render_to_response("editprofile.html", context)


def userpage(request, uid):
    if request.method == "POST":
        gear_api.new_bike(request,
            escape_and_strip(request.POST.get("type")),
            escape_and_strip(request.POST.get("make")),
            escape_and_strip(request.POST.get("model")),
            escape_and_strip(request.POST.get("year")),
            escape_and_strip(request.POST.get("photourl")),
            escape_and_strip(request.POST.get("frame", "")),
            escape_and_strip(request.POST.get("fork", "")),
            escape_and_strip(request.POST.get("wheels", "")),
            escape_and_strip(request.POST.get("components", "")),
            escape_and_strip(request.POST.get("description", "")))
        return HttpResponseRedirect("/riders/%s/" % (uid))

    showuser = people_api.get_user_by_uid(uid)
    if not showuser:
        return errorpage("Can not find user %s" % (uid))

    pagesize = 8
    res = routes_api.get_routes_by_uid(request, showuser.uid, pagesize, None)

    context = {"showuser": showuser,
               "routes": res["routes"],
               "cursor": res["end_cursor"],
               "pagesize_routes": pagesize,
               "pagesize_rides": 20,
               "biketypes": gear_api.get_bike_types(),
               "subtitle": "%s %s"%(_("Riders"),showuser.name),
               }
    return render_to_response("riderhome.html", context)


def main():
    pass

if __name__ == '__main__':
    main()
